package com.dubbo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.function.Consumer;

public final class ExceptionUtils {

  private static final Logger logger = LoggerFactory.getLogger(ExceptionUtils.class);


  public static void ignoreEx(Consumer consumer) {
    try {
      consumer.accept(null);
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }

  public static String getStackTrace(Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    e.printStackTrace(writer);
    writer.flush();
    return sw.toString();
  }

  public static void reThrowRuntimeException(Throwable t) {
    if (t instanceof Error) {
      throw (Error) t;
    }
    if (t instanceof RuntimeException) {
      throw (RuntimeException) t;
    }
    throw new RuntimeException(t);
  }

  public static RuntimeException propagateAsUncheck(Throwable t) {
    if (t instanceof Error) {
      throw (Error) t;
    }
    if (t instanceof RuntimeException) {
      throw (RuntimeException) t;
    }
    return new RuntimeException(t);
  }

  public static void handleReflectException(Exception ex) {
    if (ex instanceof NoSuchMethodException) {
      throw new IllegalStateException("Method not found: " + ex.getMessage());
    }

    if (ex instanceof IllegalAccessException) {
      throw new IllegalStateException("Could not access method: " + ex.getMessage());
    }

    if (ex instanceof ClassNotFoundException) {
      throw new IllegalStateException("Could not find class: " + ex.getMessage());
    }

    if (ex instanceof InstantiationException) {
      throw new IllegalStateException("Could not instance object: " + ex.getMessage());
    }

    reThrowRuntimeException(ex);
  }
}
